package com.gmss.crawler.utils;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * excel工具类
 */
@Slf4j
public class ExcelUtils {

    /**
     * 数据定入excel
     *
     * @param fileName      文件名
     * @param localFilePath 文件路径
     * @param rows          写入数据
     * @return
     */
    public static boolean saveExcel(String fileName, String localFilePath, List<LinkedHashMap<String, Object>> rows) {
        if (CollectionUtils.isEmpty(rows))
            return false;
        ExcelWriter writer = null;
        try {
            // 临时文件写入到服务器路径里
            File localFile = new File(localFilePath);
            if (!localFile.exists())
                localFile.mkdirs();
            File file = new File(localFilePath + File.separator + fileName);
            if (!file.exists())
                file.exists();
            writer = ExcelUtil.getWriter(localFilePath + File.separator + fileName);
            writer.write(rows);

        } catch (Exception e) {
            log.error("上传文件{}到文件服务器异常：{}", localFilePath, e);
            return false;
        } finally {
            writer.close();
        }
        return true;
    }

    /**
     * 导出单个sheet页和多个sheet页的excel
     *
     * @param fileName      文件名
     * @param localFilePath 文件路径
     * @param rows          导出的数据
     * @param sheetNumber   一个sheet页里保存的行数
     * @return
     */
    public static boolean exportExcel(String fileName, String localFilePath, List<LinkedHashMap<String, Object>> rows, Integer sheetNumber) {
        if (CollectionUtils.isEmpty(rows))
            return false;

        if (null == sheetNumber)
            sheetNumber = 65535;
        //        sheet页存放的数据量
        Integer pages = 0;
        if (rows.size() > sheetNumber) {
            pages = CommonUtils.getPages(rows.size(), sheetNumber);
        }

        // 临时文件写入到服务器路径里
        File localFile = new File(localFilePath);
        if (!localFile.exists())
            localFile.mkdirs();
        File file = new File(localFilePath + File.separator + fileName);
        if (!file.exists())
            file.exists();
        ExcelWriter writer = null;
        try {
            writer = ExcelUtil.getWriter(localFilePath + File.separator + fileName);
            if (pages <= 1) {
                writer.write(rows);
                return true;
            }
            // 如果重新设置sheet名称，需要先重命名第一个sheet页，否则第一个sheet页名称为sheet1
//            writer.renameSheet(0, "sheet-" + 1);
            for (int i = 0; i < pages; i++) {
                writer.setSheet("sheet" + (i + 1));
                List<LinkedHashMap<String, Object>> list = rows.subList(i * sheetNumber, i * sheetNumber + sheetNumber);
                writer.write(list);

            }
        } catch (Exception e) {
            log.error("写入文件异常：{}", e);
            return false;
        } finally {
            writer.flush();
            writer.close();
        }
        return true;
    }

    /**
     * 导出多个sheet页数据
     *
     * @param fileName      文件名称
     * @param localFilePath 文件路径
     * @param sheetMap      多个sheet页数据，key：sheet页名称，value：sheet数据
     * @return
     */
    public static boolean exportExcelByMultipleSheet(String fileName, String localFilePath, LinkedHashMap<String, List<LinkedHashMap<String, Object>>> sheetMap) {
        if (MapUtils.isEmpty(sheetMap))
            return false;

        // 临时文件写入到服务器路径里
        File localFile = new File(localFilePath);
        if (!localFile.exists())
            localFile.mkdirs();
        File file = new File(localFilePath + File.separator + fileName);
        if (!file.exists())
            file.exists();
        ExcelWriter writer = null;
        try {
            writer = ExcelUtil.getWriter(localFilePath + File.separator + fileName);
            for (Map.Entry<String, List<LinkedHashMap<String, Object>>> mapEntry : sheetMap.entrySet()) {
                String sheetName = mapEntry.getKey();
                List<LinkedHashMap<String, Object>> rows = mapEntry.getValue();
                writer.setSheet(sheetName);
                writer.write(rows);
            }
        } catch (Exception e) {
            log.error("写入文件异常：{}", e);
            return false;
        } finally {
            writer.flush();
            writer.close();
        }
        return true;
    }

    public static void main(String[] args) {
        List<LinkedHashMap<String, Object>> rows = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            LinkedHashMap<String, Object> row = new LinkedHashMap<>();
            row.put("标识", i);
            row.put("姓名", "姓名" + i);
            row.put("出版物名称", "出版物名称" + i);
            row.put("作者", "作者" + i);
            row.put("关键词", "关键词" + i);
            row.put("发表日期", "发表日期" + i);
            row.put("总页数", "总页数" + i);
            rows.add(row);
        }

//        exportExcel("1.xlsx", "E:\\", rows, rows.size());
////        saveExcel("1.xlsx", "E:\\", rows) ;


        LinkedHashMap<String, List<LinkedHashMap<String, Object>>> sheetMap = new LinkedHashMap<>();
        sheetMap.put("sheet1", rows);
        sheetMap.put("sheet2", rows);
        sheetMap.put("sheet3", rows);
        exportExcelByMultipleSheet("text.xlsx", "C:\\Users\\user\\Desktop", sheetMap);
    }


}
